package com.robotserver.orders.service.impl;

import com.robotserver.orders.service.RatelimitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: jianghan
 * @Date: 2021/12/8 13:54
 * @Description:
 */
@Service
public class RatelimitServiceImpl implements RatelimitService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private DefaultRedisScript<Boolean> redisScript;

    @Override
    public boolean inRateLimit(String key, Integer limitCount, Integer time) {
        List<String> keys = new ArrayList<>();
        keys.add(key);
        Boolean inRateLimit = (Boolean) stringRedisTemplate.execute(redisScript, keys, limitCount, time);
        return inRateLimit;
    }

    /**
     * 每次访问累加1,到期就清空,从0开始
     * @author jitwxs
     * @date 2023/2/14 14:15
     * @param key
     * @param liveTime
     * @return java.lang.Long
     */
    public Long incr(String key, long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, stringRedisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();

        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {//初始设置过期时间
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);
        }

        return increment;
    }
}
